import { Form, Input, Button, Icon, Radio } from "tea-component";
import React, { useState } from "react";
import { Form as FinalForm, Field } from "react-final-form";
import { getStatus } from "../../../utils/getStatus";
import { getFriendList,getGroupMemberList } from "../../..//api";
import useAsyncRetryFunc from "../../../utils/react-use/useAsyncRetryFunc";
import { debounce } from 'lodash';
import { AvatarWithProfile } from "../../../components/avatarWithProfile";


const validateValue = async (value: string,label: string) => {
  if (!value) {
    return `${label}必填`;
  }
};

export interface FormValue {
  UID: string;
}

interface Props {
  groupId:string;
  onSubmit: (formValue: FormValue) => Promise<void>;
  onSuccess?: () => void;
  onError?: () => void;
  onClose?: () => void;
}

export const TransferGroupForm = (props: Props): JSX.Element => {
  const {groupId, onSubmit, onSuccess, onError } = props;
  const { value, loading, retry } = useAsyncRetryFunc(async () => {
    if(!groupId) return;
    const frends= await getFriendList();
    // const userIds = frends.reduce((pre,cur)=>{
    //     const userid = cur.friend_profile_identifier;
    //     if(userid && pre.indexOf(userid)<0){
    //         pre.push(userid);
    //     }
    //     return pre;
    // }, []);
    // const val= await getGroupMemberList({
    //     groupId,
    //     nextSeq: 0,
    //     userIds
    // });
    // setUserList(val?.group_get_memeber_info_list_result_info_array||[])
    setUserList(frends)
    return frends;
  }, [groupId]);
    // 获取群成员列表
  const [userList,setUserList] =useState([]);
  // eslint-disable-next-line
  const _handlerSubmit = async (formValue: FormValue) => {
    try {
      await onSubmit(formValue);
      onSuccess?.();
    } catch (error) {
      onError?.();
    }
  };
  const setValue = (value) => {
    setUserList(userList.filter((item:any)=>{
      return item.friend_profile_remark.indexOf(value)!=-1||item.friend_profile_user_profile.user_profile_nick_name.indexOf(value)!=-1
    }));
}
const handleInoputOnchange = debounce(setValue, 500);
  return (
    <FinalForm onSubmit={_handlerSubmit} initialValuesEqual={() => true} initialValues={{}}>
      {({ handleSubmit, submitting, validating }) => {
        return (
          <form onSubmit={handleSubmit}>
            <Form layout="fixed" style={{ width: "100%" }}>

            <Field  name="UID"  disabled={submitting}  validateOnBlur validateFields={[]} validate={(value) => validateValue(value , '转让人UID必填')}>
                {({ input, meta }) => (
                  <Form.Item required label="转让人" status={getStatus(meta, validating)}
                    message={  getStatus(meta, validating) === "error" && meta.error } style={{height:"250px",display:"flex",overflowY:"auto"}}>
                    <section className="search-message__input-area" style={{padding:"0",marginBottom:"10px"}}>
                        <Icon className="search-message__input-area--icon" type="search" />
                        <Input className="search-message__input-area--input" type="search" placeholder="查找好友" onChange={handleInoputOnchange}/>
                    </section>
                    {
                        <Radio.Group  {...input}  layout="column">
                          {userList.map( (item:any) =>{
                            const profile = {
                                userId: item.friend_profile_user_profile.user_profile_identifier,
                                nickName: item.friend_profile_remark||item.friend_profile_user_profile.user_profile_nick_name,
                                faceUrl: item.friend_profile_user_profile.user_profile_face_url,
                                gender: item.friend_profile_user_profile.user_profile_gender,
                                role: item.friend_profile_user_profile.user_profile_role,
                            }
                            //console.log(profile);
                            return(
                            <Radio  name={item.friend_profile_identifier} >
                              <AvatarWithProfile profile={profile} />
                              <div><span className="item-left__info--name">{profile.nickName || profile.userId}</span></div>
                            </Radio >
                            ) 
                          })}
                        </Radio.Group>
                  }
                  </Form.Item>
                )}
              </Field>  
            </Form>
            <Form.Action>
              <Button  style={{borderRadius: '4px'}} type="primary"  htmlType="submit"  loading={submitting} >
                确认
              </Button>
            </Form.Action>
          </form>
        );
      }}
    </FinalForm>
  );
};
